//
//  HYFOAuthController.m
//  MyOCWeibo
//
//  Created by 黄勇锋 on 16/10/5.
//  Copyright © 2016年 黄勇锋. All rights reserved.
//

#import "HYFOAuthController.h"
#import "AFNetworking.h"
#import "AFHTTPSessionManager.h"
#import "HYFTabBarController.h"
#import "AppDelegate.h"
#import "HYFAccountTool.h"

#define  AppKey         @"266264843"
#define  AppSecret      @"b5a356d296c6db3b5316ac7c859e9f9d"
#define  redirect_uri   @"http://www.baidu.com"


@interface HYFOAuthController ()<UIWebViewDelegate>

@end

@implementation HYFOAuthController

- (void)viewDidLoad {
    [super viewDidLoad];
    

    UIWebView *webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
    webView.delegate = self;
    
    [self.view addSubview:webView];
    
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",AppKey,redirect_uri];
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
    
    [webView loadRequest:request];
}


#pragma mark - webViewDelegate
//告诉 webView 是否加载某个 request
/**
    return YES, 加载回调页 http://www.baidu.com
    return NO,  不加载回调页,我们不需要加载回调页,只要拦截 code 即可.
 */

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    NSString *urlStr = request.URL.absoluteString;
    //如果判断是要回调授权成功页的话,返回NO,并且获取 code(授权码)
    //http://www.baidu.com/?code=605990a885ab9c010e48113c54319e02
    // 要截取的字符串               605990a885ab9c010e48113c54319e02
    if ([urlStr hasPrefix:redirect_uri]) {
        
        NSRange range = [urlStr rangeOfString:@"code="];
        
        NSString *code = [urlStr substringFromIndex:range.location + range.length];
        
        //拿到访问令牌之后,获取访问令牌  accessToken
        [self getAccessTokenWithCode:code];
        
        return NO;
    }
    
    return YES;
}



//请求    accessToken
- (void)getAccessTokenWithCode:(NSString *)code{
    
    /*
     必选	类型及范围	说明
     client_id	true	string	申请应用时分配的AppKey。
     client_secret	true	string	申请应用时分配的AppSecret。
     grant_type	true	string	请求的类型，填写authorization_code
     code	true	string	调用authorize获得的code值。
     redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
     */
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //指定可以接受的序列化格式.
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"text/plain", nil];
    
    NSString *urlStr = @"https://api.weibo.com/oauth2/access_token";
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"client_id"] = AppKey;
    dict[@"client_secret"] = AppSecret;
    dict[@"grant_type"] = @"authorization_code";
    dict[@"code"] = code;
    dict[@"redirect_uri"] = redirect_uri;
    
    [manager POST:urlStr parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        HYFAccount *account = [HYFAccount accountWithDict:responseObject];
        
        [HYFAccountTool saveAccount:account];
        
        //跳转到主界面
        HYFTabBarController *tabCtrl = [[HYFTabBarController alloc]init];
        //通过这句代码取出来的 window 在某些情况下,有可能不是 appdelegate 里面的 window  (UIAlertController 弹出来的情况下,点击enter 获取的 window 就不是 )
//        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        UIWindow *window = ((AppDelegate *)[UIApplication sharedApplication].delegate).window;
        
        window.rootViewController = tabCtrl;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
    }];
    
}



@end
